<?php
/**
 * 事件监听器监听事件模型
 */
namespace App\Observers;

use App\Models\Topic;
use App\Jobs\TranslateSlug;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class TopicObserver
{
    public function saving(Topic $topic)
    {
        // 对话题内容进行XSS过滤 -> 防止XSS攻击
        $topic->body = clean($topic->body, 'user_topic_body');

        // 生成话题摘录
        $topic->excerpt = make_excerpt($topic->body);

    }

    /**
     * 事件发生在创建和编辑时、数据入库以后
     */
    public function saved(Topic $topic)
    {
        // 如果 slug 字段无内容，用翻译器对 title 进行翻译
        if ( ! $topic->slug) {

            // 推送任务到队列
            dispatch(new TranslateSlug($topic));
        }
    }

    /**
     * 当删除话题时，同时删除该话题下的所有回复
     */
    public function deleted(Topic $topic)
    {
        \DB::table('replies') -> where('topic_id', $topic->id) -> delete();
    }

}